#!/usr/bin/env python3
"""
验证依赖包兼容性脚本

检查 requirements.txt 和 pyproject.toml 中的依赖包是否兼容 Python 3.10+
"""

import sys
import subprocess
import pkg_resources
from pathlib import Path
from typing import List, Dict, Tuple


def parse_requirements(requirements_file: Path) -> List[str]:
    """解析 requirements.txt 文件"""
    requirements = []
    
    if not requirements_file.exists():
        print(f"❌ 文件不存在: {requirements_file}")
        return requirements
    
    with open(requirements_file, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            # 跳过注释和空行
            if line and not line.startswith('#'):
                requirements.append(line)
    
    return requirements


def check_python_version():
    """检查 Python 版本"""
    version = sys.version_info
    print(f"🐍 当前 Python 版本: {version.major}.{version.minor}.{version.micro}")
    
    if version.major == 3 and version.minor >= 10:
        print("✅ Python 版本符合要求 (3.10+)")
        return True
    else:
        print("❌ Python 版本不符合要求，需要 3.10+")
        return False


def check_package_availability(package_spec: str) -> Tuple[bool, str]:
    """检查包是否可用"""
    try:
        # 解析包名和版本要求
        req = pkg_resources.Requirement.parse(package_spec)
        package_name = req.project_name
        
        # 尝试获取包信息
        try:
            installed = pkg_resources.get_distribution(package_name)
            if req.specifier.contains(installed.version):
                return True, f"已安装 {installed.version}"
            else:
                return False, f"版本不匹配: 已安装 {installed.version}, 需要 {req.specifier}"
        except pkg_resources.DistributionNotFound:
            return False, "未安装"
            
    except Exception as e:
        return False, f"解析错误: {str(e)}"


def main():
    """主函数"""
    print("🔍 KidsBuddy 依赖包兼容性检查")
    print("=" * 50)
    
    # 检查 Python 版本
    if not check_python_version():
        sys.exit(1)
    
    print()
    
    # 检查项目根目录
    project_root = Path(__file__).parent.parent
    requirements_file = project_root / "requirements.txt"
    
    print(f"📋 检查依赖文件: {requirements_file}")
    
    # 解析依赖
    requirements = parse_requirements(requirements_file)
    
    if not requirements:
        print("❌ 没有找到有效的依赖包")
        sys.exit(1)
    
    print(f"📦 找到 {len(requirements)} 个依赖包")
    print()
    
    # 检查每个包
    available_count = 0
    unavailable_packages = []
    
    for req in requirements:
        available, status = check_package_availability(req)
        
        if available:
            print(f"✅ {req}: {status}")
            available_count += 1
        else:
            print(f"❌ {req}: {status}")
            unavailable_packages.append(req)
    
    print()
    print("=" * 50)
    print(f"📊 检查结果:")
    print(f"   ✅ 可用: {available_count}")
    print(f"   ❌ 不可用: {len(unavailable_packages)}")
    
    if unavailable_packages:
        print()
        print("🔧 建议安装缺失的包:")
        print("   pip install " + " ".join(f'"{pkg}"' for pkg in unavailable_packages))
        
        print()
        print("💡 或者安装完整开发环境:")
        print("   pip install -e \".[dev]\"")
    
    print()
    print("✅ 检查完成!")


if __name__ == "__main__":
    main()
